import Base from 'models/base';

import SystemUtil from 'utils/systemUtil';

class GoodsModel {
  constructor(obj) {
    this.id = obj.goodsModelId;
    this.name = obj.goodsModelName;
    this.price = obj.goodsModelSalePrice;
    this.sourcePrice = obj.goodsModelSourcePrice;

    let count = obj.stockCount;
    if (SystemUtil.isEmpty(count)) {
      count = 0;
    }
    this.count = count;

    let salesCount = obj.salesCount;
    if (SystemUtil.isEmpty(salesCount)) {
      count = 0;
    }
    this.salesCount = salesCount;
  }
}

export default class ShopGoodsModel extends Base {
  constructor(goods, buyRecord) {
    super();

    this.id = goods.goodsDefId;
    this.name = goods.goodsName;
    this.pic = this.getOnePic(goods.goodsPic);

    let models = goods.goodsModelList;
    let modelList = [];
    let modelArr = [];
    let curModel = null;
    for (let i = 0; i < models.length; i++) {
      let obj = models[i];
      obj = new GoodsModel(obj);
      modelList.push(obj);

      if (curModel === null && obj.count !== 0) {
        curModel = obj;
      }

      let arr;
      if (i % 3 === 0) {
        arr = [];
        modelArr.push(arr);
      } else {
        arr = modelArr[modelArr.length - 1];
      }
      arr.push(obj);
    }
    this.modelList = modelList;
    this.curModel = curModel;
    this.modelArr = modelArr;

    if (curModel !== null) {
      if (buyRecord === undefined) {
        this.buyCount = 1;
        return;
      }

      let modelId = curModel.id;
      let record = buyRecord.getRecordByModelId(modelId);
      if (record === null) {
        this.buyCount = 1;
      } else {
        this.buyCount = record.buyCount;
      }
    }
  }

  resetBuyCount(buyRecord) {
    let curModel = this.curModel;
    if (curModel === null) {
      return;
    }

    let modelId = curModel.id;
    let record = buyRecord.getRecordByModelId(modelId);
    if (record !== null) {
      this.buyCount = record.buyCount;
    }
  }

  checkValid() {
    if (this.curModel === null) {
      return 'curModel';
    }

    let buyCount = this.buyCount;
    if (buyCount === undefined) {
      return 'buyCount';
    }

    let count = this.curModel.count;
    if (buyCount > count) {
      return 'buyCount>count';
    }
    return '';
  }

  getObject() {
    let curModel = this.curModel;
    let postData = {
      goodsDefId: this.id,
      goodsModelId: curModel.id,
      buyCount: this.buyCount
    };
    return postData;
  }

  getBuyGoods() {
    let curModel = this.curModel;
    let postData = {
      goodsDefId: this.id,
      goodsModelId: curModel.id,
      buyCount: this.buyCount
    };
    return postData;
  }
}
